package com.lw.leetcode.str.a;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1592. 重新排列单词间的空格
 *
 * @author liw
 * @version 1.0
 * @date 2022/9/7 9:26
 */
public class ReorderSpaces {

    public static void main(String[] args) {
        ReorderSpaces test = new ReorderSpaces();

        // "this   is   a   sentence"
//        String str = "  this   is  a sentence ";

        // "practice   makes   perfect "
//        String str = " practice   makes   perfect";

        // "hello   world"
//        String str = "hello   world";

        // "walks  udp  package  into  bar  a "
//        String str = "  walks  udp package   into  bar a";

        // "a"
        String str = "a";

        String s = test.reorderSpaces(str);
        System.out.println("&" + s + "&");
    }

    public String reorderSpaces(String text) {
        String[] s = text.split(" ");
        int length = text.length();
        int l = 0;
        List<String> list = new ArrayList<>(s.length);
        for (String s1 : s) {
            if (s1.length() > 0) {
                list.add(s1);
                l += s1.length();
            }
        }
        int size = list.size() - 1;
        l = length - l;
        int a = size == 0 ? 0 : l / size;
        int b = size == 0 ? l : l % size;
        StringBuilder sb = new StringBuilder(length);
        StringBuilder sb1 = new StringBuilder(a);
        for (int i = 0; i < a; i++) {
            sb1.append(" ");
        }
        String as = sb1.toString();
        sb.append(list.get(0));
        for (int i = 1; i <= size; i++) {
            sb.append(as);
            sb.append(list.get(i));
        }
        for (int i = 0; i < b; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }

}
